/**
 * Created with IntelliJ IDEA.
 * Description: leetcode.简单题.重新排列单词间的空格
 */

class Solution {
    public static String reorderSpaces(String text) {
        StringBuffer stringBuffer = new StringBuffer();
        int count1 = 0;
        int count2 = 0;
        for(int i = 0; i < text.length(); i++) {
            if(text.charAt(i) == ' ') {
                count1++;
            }
            if((i != 0 && text.charAt(i - 1) != ' ' && text.charAt(i) == ' ') || (text.charAt(i) != ' ' && i == text.length() - 1)) {
                count2++;
            }
        }
        int merchant = 0;
        int remainder = 0;
        if(count2 - 1 != 0) {
            merchant = count1 / (count2 - 1);
            remainder = count1 % (count2 - 1);
        } else {
            merchant = 0;
            remainder = count1;
        }

        int temp = 0;
        for(int i = 0; i < text.length(); i++) {
            if(i != 0 && (text.charAt(i - 1) != ' ' && text.charAt(i) == ' ') && temp < count2 - 1) {
                temp++;
                for(int j = 0; j < merchant; j++) {
                    stringBuffer.append(' ');
                }
            }
            if(text.charAt(i) == ' ') {
                continue;
            }
            stringBuffer.append(text.charAt(i));
        }
        for(int i = 0; i < remainder; i++) {
            stringBuffer.append(' ');
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) {
        String string = reorderSpaces(" practice   makes   perfect");
    }
}

public class Test {
}
